const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const logger = require('koa-logger')
const koaBody = require('koa-body');
const path = require("path")
const cors = require('koa2-cors')
//app.use(cors())

const index = require('./routes/index')
const play = require('./routes/play')
const mine = require('./routes/mine')
const login = require('./routes/login')
const adminVerify = require('./routes/adminVerify')
const paintings = require('./routes/paintings')
const admin = require('./routes/admin')
const user = require('./routes/user')
const qa = require('./routes/qa')
const data = require('./routes/data')
const author = require('./routes/author');



// error handler
onerror(app)

app.use(async(ctx,next)=>{
   ctx.set('Access-Control-Allow-Origin','*');
   ctx.set('Access-Control-Allow-Headers','authorization,Content-type');
   ctx.set('Access-Control-Allow-Methods','PUT,POST,GET,DELETE,OPTIONS');
   ctx.set('access-control-request-headers', '*');
   if(ctx.method == 'OPTIONS'){
     ctx.body = 200;
   }else{
    await next();
   }
})

// middlewares
// app.use(bodyparser({
//   enableTypes:['json', 'form', 'text']
// }))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))
app.use(koaBody({
  multipart:true,
  formidable:{
    uploadDir:path.join(__dirname,'./public/data/images'),
    keepExtensions:true,
    maxFieldsSize:2*1024*1024
  }
}))
app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(play.routes(), play.allowedMethods())
app.use(login.routes(), login.allowedMethods())
app.use(mine.routes(), mine.allowedMethods())
app.use(adminVerify.routes(), adminVerify.allowedMethods())
app.use(paintings.routes(), paintings.allowedMethods())
app.use(admin.routes(), admin.allowedMethods())
app.use(user.routes(), user.allowedMethods())
app.use(qa.routes(), qa.allowedMethods())
app.use(data.routes(), data.allowedMethods())
app.use(author.routes(), author.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app

